package com.剑指offer.第四章;

/**
 * 合理应用哨兵节点，就不需要单独处理这些特殊的输入
 */
public class ListNodeTest {

    public ListNode head;

    /**
     * 使用哨兵节点简化操作
     *
     * @param val
     */
    public void append(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode node = dummy;
        ListNode newNode = new ListNode(val);
        while (node.next != null) {
            node = node.next;
        }
        node.next = newNode;
        this.head = dummy.next;
    }


    public void remove(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode node = dummy;

        while (node.next != null) {
            if (node.next.val == val) {
                node.next = node.next.next;
                break;
            }
            node = node.next;
        }
        this.head = dummy.next;
    }

    public ListNode convert(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            // 先将下一个节点保存下来，防止链表断开找不到
            ListNode next = cur.next;
            // 指向前一个节点
            cur.next = pre;
            // 记录当前节点 用于下个节点指向它
            pre = cur;
            cur = next;

        }
        return pre;
    }

}
